<template>
    <ModalCom v-bind="$attrs" title="添加菜单" width="520px" @open="modalOpen" :inner-loading="innerLoading" :ok-async="okAsync">
      <Form ref="formFieldsRef" :list="state.controlList" :fields="state.fields"></Form>
    </ModalCom>
</template>

<script setup>
import { reactive, ref } from "vue"
// 跨级组件
import ModalCom from "@/components/modal/index.vue"
import Form from "@/components/form/index.vue"
// messge
import { message } from "ant-design-vue"
// 校验函数
import { validateRequired, validatePassword } from "@/utils/index"
// api
import { menuCreate, menuupdate } from "@/api/menu"
// props
const props = defineProps({
  type: {
    type: String,
    defualt: ''
  },
  row: {
    type: Object,
    defualt: () => ({})
  }
})


// formFieldsRef
const formFieldsRef = ref(null)
const state = reactive({
  controlList: [
    { 
      label: "父级菜单", 
      field: "parent_menu", 
      control: "input", 
      disabled: true,
    },
    { 
      label: "菜单名称", 
      field: "menu_name_cn", 
      control: "input", 
      maxlength: 20,
      rules: [validateRequired("请输入菜单名称")]
    },
    { 
      label: "菜单路由", 
      field: "router_path", 
      control: "input",
      rules: [validateRequired("请输入菜单路由")]
    },
  ],
  fields: {
    parent_menu: "",
    menu_name_cn: "",
    router_path: "",
    parent_id: 0
  }
})

const okAsync = () => {
  return new Promise((resolve, reject) => { // then，catch
    formFieldsRef.value.validataForm().then(() => {
      if(props.type === 'edit') {
        menuupdate({
          ...state.fields,
          menu_id: props.row.menu_id
        }).then((res) => {
          message.success(res?.msg)
          resolve()
        }).catch(() => {
          reject()
        })
        return
      }
      // 添加子级
      const params = {
        ...state.fields,
        parent_id: props.type === 'addsub' ? props.row?.menu_id: 0
      }
      // 添加一级
      menuCreate(params).then((res) => {
        message.success(res?.msg)
        resolve()
      }).catch(() => {
        reject()
      })

    }).catch(() => {
      reject()
    })
  })
}

const innerLoading = () => {
  state.controlList[0].hidden = !(props.row?.parent_id === 0 && props.type === 'addsub')
  // 父级菜单名称
  state.fields.parent_menu = props.row?.menu_name_cn
  if(props.type === 'edit') {
    state.fields.menu_name_cn = props.row?.menu_name_cn
    state.fields.router_path = props.row?.router_path
  }
  return new Promise((resolve, reject) => { // then，catch
    setTimeout(() => {
      resolve()
    }, 500)
  })
}
const modalOpen = () => {
    console.log('打开了')
}
</script>